package ferri.lorenzo;

import java.util.LinkedList;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiManager;
import android.os.*;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class DiscovererActivity extends Activity {
	
	private static final String TAG = "udp";
	ListView listView;
	recvThread thr = null;
	Context c = this;
	String Address;
	ProgressDialog dialog;
	boolean[] truefalse;
	LinkedList<String> IpAdresses = new LinkedList<String>();
	LinkedList<String> host = new LinkedList<String>();
	LinkedList<String> MAC = new LinkedList<String>();
	int posizione=0;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main1);
		listView = (ListView) findViewById(R.id.ble);

		
	}
	
	@Override
	public void onStop() {
		super.onStop();
		
	}

	@Override
	protected void onPause() {
		super.onPause();
	
	}

	@Override
	protected void onResume() {
		super.onResume();

		host.clear();
		IpAdresses.clear();
		MAC.clear();

	}

	@Override
	protected void onStart() {
		super.onStart();

		final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		Log.d("INFO", "" + wm.getConnectionInfo());

		if (wm.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {
			Handler handler = new MyHandler();
		
			thr = new recvThread(handler);
			thr.start();
			dialog = ProgressDialog.show(this, "Indeterminate",
					"Indeterminate Message", false, true,
					new DialogInterface.OnCancelListener() {

						public void onCancel(DialogInterface dialog) {
							Toast.makeText(DiscovererActivity.this, "Interrupted",
									Toast.LENGTH_LONG).show();

						}

					});
			truefalse = new boolean[thr.getNumIp()];
			for (int i = 0; i < thr.getNumIp(); i++) {
				truefalse[i] = false;

			}
		} else {

			// Visualizziamo la corrispondente Dialog
			AlertDialog alertDialog = new AlertDialog.Builder(DiscovererActivity.this)
					.create();
			alertDialog.setTitle("Nessuna rete connessa");
			alertDialog.setMessage("Connettere ad una rete?");
			alertDialog.setButton("Si", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					Intent intent = new Intent(
							WifiManager.ACTION_PICK_WIFI_NETWORK);
					startActivity(intent);

				}
			});

			alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					//Close the application
					finish();

				}
			});
			alertDialog.show();

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void Vai(View view) {

		switch (view.getId()) {
		case R.id.vai:
			if (IpAdresses.size() > 0) {
				Log.d(TAG, "Stopping server ....");

				String[] ip = new String[IpAdresses.size()];
				String[] Hostname = new String[IpAdresses.size()];
				for (int i = 0; i < IpAdresses.size(); i++) {
					ip[i] = IpAdresses.get(i);
					Hostname[i] = host.get(i);
				}

				Intent i = new Intent();
				i.putExtra("id", posizione);
				i.putExtra("allip", ip);
				setResult(RESULT_OK, i);
		        finish();
			} else {
				// Visualizziamo la corrispondente Dialog
				AlertDialog alertDialog = new AlertDialog.Builder(
						DiscovererActivity.this).create();
				alertDialog.setTitle("Nessun dispositivo disponibile");
				alertDialog.setMessage("Uscire?");
				alertDialog.setButton("Si",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

								setResult(RESULT_CANCELED);
								finish();

							}
						});

				alertDialog.setButton2("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int which) {

								// here you can add functions

							}
						});
				alertDialog.show();
			}
			break;
		case R.id.aggio:
			onStart();
		}

	}

	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			if (bundle.containsKey("refresh")) {

				//Array of devices
				String[] arrayData = bundle.getStringArray("refresh");

				//Create l'ArrayAdapter
				ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(c,
						android.R.layout.simple_list_item_checked, arrayData);

				//Set multi-selection mode
				listView.setChoiceMode(2);
				listView.setAdapter(arrayAdapter);
				
				//Array of selected and unselected devices
				truefalse = new boolean[thr.getNumIp()];
				
				for (int i = 0; i < thr.getNumIp(); i++) {
					truefalse[i] = false;

				}
				dialog.dismiss();

				OnItemClickListener listener = new OnItemClickListener() {
					@SuppressWarnings("rawtypes")
					public void onItemClick(AdapterView parent, View v,
							int position, long id) {
						posizione=position;
						
						if (!listView.getItemAtPosition(position).toString()
								.startsWith("nessun")) {

							if (truefalse[position]) {
								truefalse[position] = false;
								//remove Device from the list
								host.remove(thr.getHostName(position));
								IpAdresses.remove(thr.getIpAddress(position));
								MAC.remove(thr.getMAC(position));

							} else {
								truefalse[position] = true;
								//Add device to list
								MAC.add(thr.getMAC(position));
								IpAdresses.add(thr.getIpAddress(position));
								host.add(thr.getHostName(position));
							}
							Log.i("CHECK", "Checked: " + truefalse[position]
									+ " pos:" + position + " id:" + id);
						} 
					}
				};
				listView.setOnItemClickListener(listener);
			}

		}

	}
}
